import { useEditorStore } from '@/store/editor';
import { useKeyPress } from 'ahooks';

// 没有聚焦input框才触发快捷键
function isValid() {
  const active = document.activeElement;
  if (active === document.body) return true;
  if (active?.matches('div[role="button"]')) return true; // 受到 dnd-kit 影响,需要添加这行代码
  return false;
}

function usePress(keys: string[], callback: Function) {
  useKeyPress(keys, () => {
    if (isValid() === false) return;
    callback();
  });
}

export function useCanvasKeyPress() {
  const { deleteById, copy, paste, selectNextOrPrev } = useEditorStore();

  // 删除的快捷键
  usePress(['backspace', 'delete'], () => {
    deleteById();
  });

  //复制
  usePress(['ctrl.c', 'meta.c'], () => {
    copy();
  });

  //粘贴
  usePress(['ctrl.v', 'meta.v'], () => {
    paste();
  });

  // 向上选择
  usePress(['uparrow'], () => {
    selectNextOrPrev('prev');
  });

  // 向下选择
  usePress(['downarrow'], () => {
    selectNextOrPrev('next');
  });
}
